<template>
  <ContentWrap v-if="isSuperAdmin">
    <div :class="searchVisible ? 'flex flex-row flex-wrap mb-2' : 'flex flex-row flex-wrap'">
      <el-button v-if="showBack" @click="router.back()">
        <Icon icon="ep:arrow-left" class="mr-5px"/>
        返回
      </el-button>
      <el-button
        plain
        type="primary"
        @click="openForm()"
        v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']"
      >
        <Icon class="mr-5px" icon="ep:plus"/>
        新增
      </el-button>
      <el-button plain type="success" @click="searchVisible = !searchVisible">
        <Icon class="mr-5px" icon="ep:operation"/>
        {{ searchVisible ? '关闭筛选' : '打开筛选' }}
      </el-button>
      <el-text type="info">
        <span class="ml-5px">{{ searchVisible ? '关闭以下筛选条件' : '点击打开筛选条件' }}</span>
      </el-text>
      <div class="flex-1"></div>
      <el-button @click="resetQuery">
        <Icon class="mr-5px" icon="ep:refresh"/>
        刷新列表
      </el-button>
    </div>
    <el-form
      v-if="searchVisible"
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="关键词" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入关键词称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="商家类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择商家类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SHOP_OWNER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="行业类目" prop="categoryCode">
        <el-select
          v-model="queryParams.categoryCode"
          placeholder="请选择行业类目"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SHOP_CATEGORY_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话" prop="contactMobile">
        <el-input
          v-model="queryParams.contactMobile"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="经营状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择经营状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SHOP_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="省市区县" prop="regionCode">
        <RegionPicker v-model="queryParams.regionCode" :selectAnyLevel="true" class="!w-240px"/>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select
          v-model="queryParams.auditStatus"
          placeholder="请选择审核状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.AUDIT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="入驻时间" prop="enterTime">
        <el-date-picker
          v-model="queryParams.enterTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="过期时间" prop="expireTime">
        <el-date-picker
          v-model="queryParams.expireTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['shop:info:export']"
        >
          <Icon icon="ep:download" class="mr-5px"/>
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column label="基本信息" align="left" min-width="220px">
        <template #default="scope">
          <div class="flex items-center">
            <dict-tag :type="DICT_TYPE.SHOP_OWNER_TYPE" :value="scope.row.type"/>
            <el-image
              fit="cover"
              title="[徽标]"
              :src="scope.row.logo || '/placeholder.png'"
              :preview-src-list="[scope.row.logo || '/placeholder.png']"
              :initial-index="0"
              :preview-teleported="true"
              :hide-on-click-modal="true"
              class="flex-none w-15px h-15px ml-[5px] cursor-pointer"
            />
            <span class="mx-[5px] font-bold">{{ scope.row.name }}</span>
            <el-tag v-if="scope.row.selfOperated" type="primary">自营</el-tag>
          </div>
          <div class="flex items-center">
            <dict-tag :type="DICT_TYPE.SHOP_CATEGORY_TYPE" :value="scope.row.categoryCode"/>
            <span class="ml-5px">{{ scope.row.categoryName || '不详' }}</span>
          </div>
          <div class="flex items-center">
            <span>{{ scope.row.provinceCityCounty }}{{ scope.row.detailAddress }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="用户信息" align="center" min-width="100px">
        <template #default="scope">
          <el-tooltip :content="'用户编号：' + scope.row.userId" placement="top">
            <div class="flex flex-col items-center">
              <el-avatar :src="scope.row.user?.avatar || './avatar.png'"/>
              <el-text>{{ scope.row.user?.nickname || '未知' }}</el-text>
              <el-text>{{ scope.row.user?.mobile || '手机号未绑定' }}</el-text>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="联系人信息" align="center" min-width="120px">
        <template #default="scope">
          <el-tooltip :content="'用户编号：' + scope.row.userId" placement="top">
            <el-text>{{ scope.row.contactName || '不详' }}</el-text>
          </el-tooltip>
          <br/>
          <el-text>{{ scope.row.contactMobile || '不详' }}</el-text>
          <br/>
          <el-image
            fit="cover"
            title="[营业执照]"
            :src="scope.row.businessLicenseUrl || '/placeholder.png'"
            :preview-src-list="[scope.row.businessLicenseUrl || '/placeholder.png']"
            :initial-index="0"
            :preview-teleported="true"
            :hide-on-click-modal="true"
            class="flex-none w-30px h-30px cursor-pointer"
          />
          <el-image
            fit="cover"
            title="[身份证正面]"
            :src="scope.row.ownerEidFrontUrl || '/placeholder.png'"
            :preview-src-list="[scope.row.ownerEidFrontUrl || '/placeholder.png']"
            :initial-index="0"
            :preview-teleported="true"
            :hide-on-click-modal="true"
            class="flex-none w-30px h-30px ml-5px cursor-pointer"
          />
          <el-image
            fit="cover"
            title="[身份证反面]"
            :src="scope.row.ownerEidBackUrl || '/placeholder.png'"
            :preview-src-list="[scope.row.ownerEidBackUrl || '/placeholder.png']"
            :initial-index="0"
            :preview-teleported="true"
            :hide-on-click-modal="true"
            class="flex-none w-30px h-30px ml-5px cursor-pointer"
          />
        </template>
      </el-table-column>
      <el-table-column label="商家收款码" align="center" width="85px">
        <template #default="scope">
          <el-image
            fit="cover"
            title="[商家收款码]"
            :src="scope.row.qrcodeImage || '/placeholder.png'"
            :preview-src-list="[scope.row.qrcodeImage || '/placeholder.png']"
            :initial-index="0"
            :preview-teleported="true"
            :hide-on-click-modal="true"
            class="flex-none w-70px h-70px ml-5px cursor-pointer"
          />
        </template>
      </el-table-column>
      <el-table-column label="联盟豆/收益豆" align="left" min-width="220px">
        <template #default="scope">
          <p
          >冻结中：<span class="color-red-500">{{
              Math.floor(scope.row.cryptocurrencyFreezing)
            }}</span></p
          >
          <p
          >累计：<span class="color-red-500">{{
              Math.floor(scope.row.cryptocurrencyGet)
            }}</span></p
          >
          <p
          >可用：<span class="color-orange-500">{{ Math.floor(scope.row.cryptocurrency) }}</span
          >（含<span class="color-orange-500">{{
              Math.floor(scope.row.cryptocurrency - scope.row.cryptocurrencyOrigin)
            }}</span
          >个收益豆）</p
          >
        </template>
      </el-table-column>
      <el-table-column label="状态" align="left" prop="statusInfo" min-width="130px">
        <template #default="scope">
          开关：
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.enabled"/>
          <br/>
          营业：
          <dict-tag :type="DICT_TYPE.SHOP_STATUS" :value="scope.row.status"/>
          <br/>
          审核：
          <dict-tag :type="DICT_TYPE.AUDIT_STATUS" :value="scope.row.auditStatus"/>
          <br v-if="scope.row.auditStatus === 2"/>
          <el-text v-if="scope.row.auditStatus === 2">原因：{{ scope.row.auditNote }}</el-text>
        </template>
      </el-table-column>
      <el-table-column label="入驻信息" align="left" prop="enterPackageName" min-width="250px">
        <template #default="scope">
          <el-text>申请时间：{{ formatDate(scope.row.createTime) || '不详' }}</el-text>
          <!-- <br />
          <el-text>入驻套餐：{{ scope.row.enterPackageName || '不详' }}</el-text> -->
          <br/>
          <el-text>入驻时间：{{ formatDate(scope.row.enterTime) || '不详' }}</el-text>
          <br/>
          <el-text>过期时间：{{ formatDate(scope.row.expireTime) || '不详' }}</el-text>
          <br/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="120">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openBasicForm(scope.row.id)"
            v-hasPermi="['shop:info:update']"
          >
            修改基础资料
          </el-button>
          <br/>
          <el-button
            link
            type="primary"
            @click="openAddressForm(scope.row.id)"
            v-hasPermi="['shop:info:update']"
          >
            修改地理位置
          </el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button type="primary" link>
              <Icon icon="ep:d-arrow-right"/>
              更多
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="openStatusForm" v-if="isShopAdmin">
                  修改营业状态
                </el-dropdown-item>
                <el-dropdown-item command="openServiceFeePercentForm" v-if="isSuperAdmin">
                  设置平台抽佣比例
                </el-dropdown-item>
                <el-dropdown-item
                  command="openDiscountPercentForm"
                  v-if="isSuperAdmin || isShopAdmin"
                >
                  设置顾客抵扣比例
                </el-dropdown-item>
                <el-dropdown-item
                  command="openAuditForm"
                  v-if="isSuperAdmin"
                  :disabled="scope.row.auditStatus === 1"
                >
                  审核
                </el-dropdown-item>
                <el-dropdown-item
                  command="openEnabledForm"
                  v-if="isSuperAdmin"
                  :disabled="scope.row.auditStatus === 0"
                >
                  {{ scope.row.enabled === 1 ? '解封' : '封禁' }}
                </el-dropdown-item>
                <!-- <el-dropdown-item
                  command="openEnterPackageForm"
                  v-if="isSuperAdmin"
                >
                  赠送套餐
                </el-dropdown-item> -->
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 必要资料表单弹窗：新增 -->
  <CreateForm v-if="isSuperAdmin" ref="createFormRef" @success="getList"/>
  <!-- 基础资料表单弹窗：修改 -->
  <BasicForm ref="basicFormRef" @success="getList"/>
  <!-- 经营地址表单弹窗：修改 -->
  <AddressForm ref="addressFormRef" @success="getList"/>
  <!-- 经营状态表单弹窗：修改 -->
  <StatusForm ref="statusFormRef" @success="getList"/>
  <!-- 服务费率表单弹窗：修改 -->
  <ServiceFeePercentForm ref="serviceFeePercentFormRef" @success="getList"/>
  <!-- 可抵扣率表单弹窗：修改 -->
  <DiscountPercentForm ref="discountPercentFormRef" @success="getList"/>
  <!-- 审核信息表单弹窗：修改 -->
  <AuditForm v-if="isSuperAdmin" ref="auditFormRef" @success="getList"/>
  <!-- 赠送套餐表单弹窗：修改 -->
  <EnterPackageForm v-if="isSuperAdmin" ref="enterPackageFormRef" @success="getList"/>
</template>

<script setup lang="ts">
import {DICT_TYPE, getIntDictOptions, getStrDictOptions} from '@/utils/dict'
import download from '@/utils/download'
import {ShopInfoApi, ShopInfoVO} from '@/api/mall/shop/info'
import CreateForm from './CreateForm.vue'
import BasicForm from './BasicForm.vue'
import AddressForm from './AddressForm.vue'
import StatusForm from './StatusForm.vue'
import ServiceFeePercentForm from './ServiceFeePercentForm.vue'
import DiscountPercentForm from './DiscountPercentForm.vue'
import AuditForm from './AuditForm.vue'
import EnterPackageForm from './EnterPackageForm.vue'
import {RegionPicker} from '@/views/universal/region'
import {formatDate} from '@/utils/formatTime'
import {checkRole} from '@/utils/permission'

/** 店铺详情 列表 */
defineOptions({name: 'ShopInfo'})

const message = useMessage() // 消息弹窗
const router = useRouter()

const searchVisible = ref(false)

const isSuperAdmin = computed(() => checkRole(['super_admin', 'platform_admin', 'tenant_admin']))
const isShopAdmin = computed(() => checkRole(['shop_admin']))

const loading = ref(true) // 列表的加载中
const list = ref<ShopInfoVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  keyword: undefined,
  type: undefined,
  categoryCode: undefined,
  contactMobile: undefined,
  ownerEidNo: undefined,
  status: undefined,
  regionCode: undefined,
  auditStatus: undefined,
  enterTime: undefined,
  expireTime: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ShopInfoApi.getShopInfoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const createFormRef = ref()
const basicFormRef = ref()
const addressFormRef = ref()
const serviceFeePercentFormRef = ref()
const discountPercentFormRef = ref()
const statusFormRef = ref()
const auditFormRef = ref()
const enterPackageFormRef = ref()

const openForm = (type?: string = undefined) => {
  createFormRef.value.open(type)
}
const openBasicForm = (id: number | string) => {
  basicFormRef.value.open('update', id)
}
const openAddressForm = (id: number | string) => {
  addressFormRef.value.open('update', id)
}

const handleCommand = (command, row: any) => {
  switch (command) {
    case 'openServiceFeePercentForm':
      openServiceFeePercentForm(row.id)
      break
    case 'openDiscountPercentForm':
      openDiscountPercentForm(row.id)
      break
    case 'openStatusForm':
      openStatusForm(row.id)
      break
    case 'openAuditForm':
      openAuditForm(row.id)
      break
    case 'openEnabledForm':
      openEnabledForm(row)
      break
    case 'openEnterPackageForm':
      openEnterPackageForm(row.id)
      break
    default:
      break
  }
}
const openServiceFeePercentForm = (id: number | string) => {
  serviceFeePercentFormRef.value.open('update', id)
}
const openDiscountPercentForm = (id: number | string) => {
  discountPercentFormRef.value.open('update', id)
}
const openStatusForm = (id: number | string) => {
  statusFormRef.value.open('update', id)
}
const openAuditForm = (id: number | string) => {
  auditFormRef.value.open('update', id)
}
const openEnabledForm = async (row: any) => {
  try {
    await message.confirm(
      '确定要对【' + row.name + '】进行【' + (row.enabled !== 0 ? '解封' : '封禁') + '】操作吗？'
    )
    await ShopInfoApi.updateEnabled({id: row.id, enabled: row.enabled !== 0})
    await getList()
  } catch {
  }
}
const openEnterPackageForm = (id: number | string) => {
  enterPackageFormRef.value.open('update', id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ShopInfoApi.exportShopInfo(queryParams)
    download.excel(data, '店铺详情.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const showBack = ref(false)
onMounted(() => {
  handleQuery()
})
</script>
